import { Loading } from 'vant';

const loadingDirective = {
  mounted(el, binding) {
    const isLoading = binding.value;
    const mask = document.createElement('div');
    mask.className = 'v-loading-mask';
    
    if (isLoading) {
      const loadingText = binding.arg || '加载中...';
      mask.innerHTML = `
        <div class="v-loading-content">
          ${Loading({ size: '24px', vertical: true, children: loadingText })}
        </div>
      `;
      el.appendChild(mask);
    }

    // 保存遮罩元素到宿主元素
    el._v_loading_mask = mask;
    el.style.position = 'relative'; // 确保定位正确
  },
  updated(el, binding) {
    const isLoading = binding.value;
    const mask = el._v_loading_mask;
    
    if (isLoading && !mask) {
      // 如果更新时 mask 不存在（比如初始值为 false），重新创建
      this.mounted(el, binding);
      return;
    }

    if (mask) {
      if (isLoading) {
        const loadingText = binding.arg || '加载中...';
        mask.innerHTML = `
          <div class="v-loading-content">
            ${Loading({ size: '24px', vertical: true, children: loadingText })}
          </div>
        `;
        mask.style.display = 'flex';
      } else {
        mask.style.display = 'none';
      }
    }
  },
  unmounted(el) {
    if (el._v_loading_mask) {
      el._v_loading_mask.remove();
    }
  },
};

export default loadingDirective;